﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using System.Diagnostics;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using System.Data;
using DoubleH.Utility.Configuration;

namespace SalesOrderS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        Table.SalesOrderS order = null;
        DataTableText tableText = DataTableText.销售单据商品编辑;

        public void Init(Table.SalesOrderS.EnumFlag flag, Table.SalesOrderS obj)
        {
            order = obj ?? new Table.SalesOrderS(flag) ;
            InitVar();

            productSListInfoObject.Init(DoubleHConfig.UserConfig.GetUserUIparams(  tableText ));
            productSListInfoObject.ShowAverage = false;
            corSelect1.Init(true);
            userSelect1.Init(Table.UserS.EnumFlag.经办人);
            uCUniqueSInvoice.Init(Table.UniqueS.EnumFlag.发票定义);

            InitMenu();
            InitEvent();
            InitOrder();
        }

        private void InitMenu()
        {
            MenuItem mi1 = new MenuItem();
            mi1.Header = "选择价格";
            mi1.Click += (ss, ee) =>
            {
                if (productSListInfoObject.SelectedItem == null)
                {
                    MessageWindow.Show("请选择商品");
                    return;
                }

                ProductS.GetWholesalePrice gwp = new ProductS.GetWholesalePrice(productSListInfoObject.SelectedItem);
                gwp.ShowDialog();
            };
            productSListInfoObject.BodyMenu.Items.Insert(0, mi1);
            productSListInfoObject.BodyMenu.Items.Insert(1, new Separator());
        }

        private void InitOrder()
        {
            Debug.Assert(order != null);

            bool b = (order.Enable > Table.SalesOrderS.EnumEnable.下单);
            dateTimeUpDownKaiDan.IsReadOnly = b;
            dateTimeUpDownDaoHuo.IsReadOnly = b;
            corSelect1.IsEnabled = !b;
            userSelect1.IsReadOnly = b;
            textBoxNote.IsReadOnly = b;

            uCStoreS1.IsEnabled = !b;
            checkBoxDefault.IsEnabled = !b;
            buttonZuoFei.IsEnabled = !b;
            buttonSave.IsEnabled = !b;
            uCUniqueSInvoice.IsEnabled = !b;
            buttonShenHe.IsEnabled = !b;
            if (order.Flag == Table.SalesOrderS.EnumFlag.销售订单)
                doubleUpDownAdvance.IsEnabled = !b;
            else
                doubleUpDownAdvance.IsEnabled = false;

            BaoXiu.IsEnabled = (order.Flag != Table.SalesOrderS.EnumFlag.销售退货单);
            dateTimeUpDownKaiDan.Value = order.OrderDateTime;
            dateTimeUpDownDaoHuo.Value = order.ArrivalDateTime;
            label1OrderNo.Content = order.OrderNO;
            corSelect1.SelectedObjectId = order.CorSId;
            userSelect1.SelectedValue = order.OperatorerSId;
            uCStoreS1.SelectedObjectId = order.StoreSId;
            textBoxStoreAddress.Text = order.Address;
            textBoxNote.Text = order.Note;
            BaoXiu.Value = (int)order.BaoXiu;
            uCUniqueSInvoice.SelectedObjectId = order.InvoiceType;
            doubleUpDownAdvance.Value = order.Advance;

            productSListInfoObject.ItemsSource = order.ProductSList;
            productSListInfoObject.IsReadOnly = false;
            switch (order.Flag)
            {
                case Table.SalesOrderS.EnumFlag.销售询价单:
                    productSListInfoObject.MustHasStoreS = false;
                    productSListInfoObject.ProductSType = ProductS.GetProductS.EnumProductS.询价单商品;
                    break;
                case Table.SalesOrderS.EnumFlag.销售退货单:
                    productSListInfoObject.MustHasStoreS = false;
                    productSListInfoObject.ProductSType = ProductS.GetProductS.EnumProductS.可销售商品;
                    break;

                default:
                    productSListInfoObject.MustHasStoreS = true;
                    productSListInfoObject.ProductSType = ProductS.GetProductS.EnumProductS.可销售商品;
                    break;
            }

            if (order.Id == -1)
                productSListInfoObject.EnableText = string.Empty;
            else
            {
                switch (order.Enable)
                {
                    case Table.SalesOrderS.EnumEnable.审核:
                    case Table.SalesOrderS.EnumEnable.入账:
                    case Table.SalesOrderS.EnumEnable.作废:
                    case Table.SalesOrderS.EnumEnable.预付款:
                        productSListInfoObject.EnableText = order.Enable.ToString();
                        productSListInfoObject.IsReadOnly = true;
                        break;
                    default:
                        productSListInfoObject.EnableText = order.Id == -1 ? string.Empty : order.Enable.ToString();
                        break;
                }
            }
        }

        private void InitVar()
        {
            switch (order.Flag)
            {
                case Table.SalesOrderS.EnumFlag.销售询价单:
                    tableText = DataTableText.销售询价单商品编辑;
                    productSListInfoObject.ShowAverage = true;
                    productSListInfoObject.CanNegativeSales = true;
                    buttonNew.Content = "询价单（新）";
                    break;
                case Table.SalesOrderS.EnumFlag.销售退货单:
                    labelDate.Content = "退货日期";
                    productSListInfoObject.Foreground = Brushes.Red;
                    buttonNew.Content = "退货单（新）";

                    break;
                case Table.SalesOrderS.EnumFlag.赠品出库单:
                    tableText = DataTableText.赠品商品编辑;
                    expanderNew.IsEnabled = false;
                    break;
                case Table.SalesOrderS.EnumFlag.销售订单:
                    buttonNew.Content = "销售单（新）";
                    break;
            }

            string name = order.Flag.ToString();
            this.Title = name;
            labelTitle.Content = name;
        }

        private void InitEvent()
        {
            uCStoreS1.SelectedObjectEvent += (ee) => ChangedStoreS(ee);
            this.Closing += (ss, ee) =>  ee.Cancel = !DataSaveOrCancel();
            corSelect1.CorSChanged += (ee) => order.CorSId = corSelect1.SelectedObjectId;
            buttonPre.Click += (ss, ee) =>  OrderPre();
            buttonNext.Click += (ss, ee) =>  OrderNext();
            doubleUpDownDefault.ValueChanged += (ss, ee) =>  ChangeQuantity(); 
            checkBoxDefault.Checked += (ss, ee) =>  ChangeQuantity();
            buttonZuoFei.Click += (ss, ee) => OrderZuoFei(); 
            buttonSave.Click += (ss, ee) =>  OrderSave(); 
            buttonShenHe.Click += (ss, ee) =>  OrderShenHe(); 
            buttonPrint.Click += (ss, ee) =>PrintFunction.Print(order, DataTableText.销售订单);

            buttonNew.Click += (ss, ee) =>
            {
                OrderNew();
                expanderNew.IsExpanded = false;
            };
            buttonCopyXJ.Click += (ss, ee) =>
                {
                    if (order.Id == -1)
                        return;

                    order = (Table.SalesOrderS)order.CloneObject(new object[]{Table.SalesOrderS.EnumFlag.销售询价单});
                    OrderCopy();
                };
            buttonCopyPF.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.SalesOrderS)order.CloneObject(new object[]{ Table.SalesOrderS.EnumFlag.销售订单});
                //order.Flag = Table.SalesOrderS.EnumFlag.销售订单;
                OrderCopy();
            };
            buttonCopyTH.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.SalesOrderS)order.CloneObject(new object[] { Table.SalesOrderS.EnumFlag.销售退货单 });
                //order.Flag = Table.SalesOrderS.EnumFlag.销售退货单;
                OrderCopy();
            };
            expanderNew.MouseLeave += (ss, ee) => { expanderNew.IsExpanded = false; };
        }

        private void ChangedStoreS(Table.StoreS ee)
        {
            productSListInfoObject.StoreS = ee;
            textBoxStoreAddress.Text = ee.Address;
        }

        private void ChangeQuantity()
        {
            if (checkBoxDefault.IsChecked == true)
                productSListInfoObject.ResetAllProductQuantity( (double)doubleUpDownDefault.Value);
        }

        private void OrderPre()
        {
            Table.SalesOrderS p = Table.SalesOrderS.GetPreObject(order.Id, order.Flag);
            if (p == null)
                MessageWindow.Show("没有上一条记录了");
            else
            {
                order = p;
                InitOrder();
            }
        }

        private void OrderNext()
        {
            FCNS.Data.Table.SalesOrderS p = Table.SalesOrderS.GetNextObject(order.Id, order.Flag);

            if (p == null)
                MessageWindow.Show("没有下一条记录了");
            else
            {
                order = p;
                InitOrder();
            }
        }

        private void OrderNew()
        {
            if (DataSaveOrCancel())
            {
                order = new FCNS.Data.Table.SalesOrderS(order.Flag) ;
                InitOrder();
            }
        }

        private void OrderZuoFei()
        {
            //如果订单还没有保存到数据库就没必要删除了,免去控件的刷新
            if (order.Id == -1)
                return;

            if (MessageWindow.Show("", "确定要作废此单据吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Table.DataTableS.EnumDatabaseStatus result = order.ZuoFei();
                MessageWindow.Show(result.ToString());
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    OrderNew();
            }
        }

        private void OrderSave()
        {
            order.OrderDateTime = (DateTime)dateTimeUpDownKaiDan.Value;
            order.ArrivalDateTime = (DateTime)dateTimeUpDownDaoHuo.Value;
            if (!string.IsNullOrEmpty(userSelect1.Text))
                order.OperatorerSId = (Int64)userSelect1.SelectedValue;

            order.StoreSId = uCStoreS1.SelectedObjectId;
            order.Address = textBoxStoreAddress.Text;
            order.Note = textBoxNote.Text;
            order.BaoXiu = BaoXiu.Value.Value;
            order.Advance = doubleUpDownAdvance.Value.Value;
            order.InvoiceType = uCUniqueSInvoice.SelectedObjectId;

            Table.DataTableS.EnumDatabaseStatus result;
            if (order.Id == -1)
                result = order.Insert();
            else
                result = order.Update();

            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                InitOrder();
            else
                MessageWindow.Show(result.ToString());
        }

        private void OrderShenHe()
        {
            if (order.Id == -1)
            {
                MessageWindow.Show("请先保存单据");
                return;
            }

            order.AuditorUserSId = Table.UserS.LoginUser.Id;
            Table.DataTableS.EnumDatabaseStatus result = order.UpdateTo(Table.SalesOrderS.EnumEnable.审核);
            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                InitOrder();
            else
                MessageWindow.Show(result.ToString());
        }

        private bool DataSaveOrCancel()
        {
            if (string.IsNullOrEmpty(label1OrderNo.Content.ToString()) && productSListInfoObject.HasItems)
            {
                switch (MessageBox.Show("是否保存单据?", "", MessageBoxButton.YesNoCancel))
                {
                    case MessageBoxResult.Yes:
                        OrderSave();
                        break;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            return true;
        }

        private void OrderCopy()
        {
            InitVar();
            order.Enable = Table.SalesOrderS.EnumEnable.下单;
            order.Id = -1;
            InitOrder();
            label1OrderNo.Content = "";
            dateTimeUpDownKaiDan.Value = DateTime.Now;
            dateTimeUpDownDaoHuo.Value = DateTime.Now;
            expanderNew.IsExpanded = false;
        }
    }
}